package com.sos.widget.binding;

import android.content.res.ColorStateList;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.BindingAdapter;

/**
 * @Description
 * @Author 梁浩文
 * @Date 2022/8/24 23:36
 */
public class LayoutBindingAdapter {

    @BindingAdapter(value = {
            "saas_marginTop", "saas_marginBottom", "saas_marginLeft", "saas_marginRight",
            "saas_paddingTop", "saas_paddingBottom", "saas_paddingLeft", "saas_paddingRight", "saas_padding",
            "saas_backgroundTint","saas_layout_height"
    }, requireAll = false)
    public static void setViewLayout(View view,
                                     Integer marginTop, Integer marginBottom, Integer marginLeft, Integer marginRight,
                                     Integer paddingTop, Integer paddingBottom, Integer paddingLeft, Integer paddingRight, Integer saas_padding,int backGroupTint,int height) {
        if (view != null) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            ViewGroup.MarginLayoutParams marginLayoutParams;
            if (layoutParams != null) {
                marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;

                if (marginTop != null) {
                    marginLayoutParams.topMargin = dp2px(view, marginTop);
                }
                if (marginBottom != null) {
                    marginLayoutParams.bottomMargin = dp2px(view, marginBottom);
                }
                if (marginLeft != null) {
                    marginLayoutParams.leftMargin = dp2px(view, marginLeft);
                }
                if (marginRight != null) {
                    marginLayoutParams.rightMargin = dp2px(view, marginRight);
                }
                if (saas_padding != null) {
                    int padding = dp2px(view, saas_padding);
                    view.setPadding(padding, padding, padding, padding);
                } else {
                    view.setPadding(paddingLeft == null ? view.getPaddingLeft() : dp2px(view, paddingLeft), paddingTop == null ? view.getPaddingTop() : dp2px(view, paddingTop),
                            paddingRight == null ? view.getPaddingRight() : dp2px(view, paddingRight), paddingBottom == null ? view.getPaddingBottom() : dp2px(view, paddingBottom));
                }
                if(height!=0){
                    marginLayoutParams.height=dp2px(view, height);
                }
                if(backGroupTint!=0){
                    view.setBackgroundTintList(ColorStateList.valueOf(backGroupTint));
                }
            }
        }
    }

    public static int dp2px(View view,int dp){
        if(dp==0){
            return 0;
        }
        float scale = view.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
}
